package per.jdz.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池示例
 * 
 * 问题： 如何设置线程数量
 * 方案：
 * 一般设置：
 * cpu密集型：线程数量 = cpu核心数量 + 1
 * io密集型：线程数量 = IO线程数量 * 2
 */
public class CustomThreadPoolDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                    2,
                    5,
                    3,
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(3),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.AbortPolicy()
                );
        try {
            // 最大承载： queueSize + maximumPoolSize
            for (int i = 0; i < 11; i++) {
                threadPool.execute(()-> {
                    System.out.println(Thread.currentThread().getName() + " ok");
                });
            }            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
